/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ipo.mm.ejb.facade.log;

import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ipo.mm.ejb.entities.Log;
import org.ipo.mm.ejb.entities.User;

/**
 *
 * @author makcro
 */
@Stateless
public class LogFacade implements LogFacadeLocal {
    @PersistenceContext
    private EntityManager em;

    public void create(Log log) {
        em.persist(log);
    }

    public void edit(Log log) {
        em.merge(log);
    }

    public void remove(Log log) {
        em.remove(em.merge(log));
    }

    public Log find(Object id) {
        return em.find(Log.class, id);
    }

    public List<Log> findAll() {
        return em.createNamedQuery("Log.findAllNotDeleted").getResultList();
    }

    public void log(User user, String message){

        Log log = new Log();
        log.setUserId(user);
        log.setAction(message);
        log.setTime(new Date(System.currentTimeMillis()));
        log.setDeleted(false);

        create(log);

    }

    public void logCreate(User user, String entityType, String entiyName){
        String message = entityType + " " + entiyName + " created.";
        log(user, message);
    }

    public void logUpdate(User user, String entityType, String entiyName){
        String message = entityType + " " + entiyName + " updated.";
        log(user, message);
    }

    public void logDelete(User user, String entityType, String entiyName){
        String message = entityType + " " + entiyName + " deleted.";
        log(user, message);
    }
    
    public Long getCount(){
        return (Long) em.createNamedQuery("Log.findCountNotDeleted").getSingleResult();
    }

    public List<Log> findAll(int firstResult, int maxResults){
        return em.createNamedQuery("Log.findAllNotDeleted").setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

}
